package com.element.security.resource.handler;

import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.security.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 如果用户已经通过身份验证，试图访问受保护的(该用户没有权限的)资源
 *
 * @auther zhangwj
 * @date 2021/3/18 下午1:47
 */
public class GoAccessDeniedHandler implements AccessDeniedHandler {

    private final Logger logger = LoggerFactory.getLogger(GoAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException {
        logger.error("AccessDeniedException异常,请求路径:{},异常信息:", request.getServletPath(), e);
        ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_ACCESS_DENIED));
    }
}
